import { _decorator, Component, RigidBody2D, Vec2, Vec3 } from 'cc';
import { BaseComponent } from './BaseComponent';

const { ccclass, property } = _decorator;

@ccclass('WanderComponent')
export class WanderComponent extends BaseComponent {
    @property
    moveSpeed: number = 5;      // 移动速度

    @property
    wanderRadius: number = 20;  // 最大游走半径

    @property({
        tooltip: "每次改变方向的最小时间间隔"
    })
    minChangeInterval: number = 2;

    @property({
        tooltip: "每次改变方向的最大时间间隔"
    })
    maxChangeInterval: number = 4;

    @property({
        tooltip: "每次改变方向的最大角度（度）"
    })
    maxTurnAngle: number = 120;

    private _rigidbody: RigidBody2D = null;
    private _originPos: Vec3 = null;
    private _currentDirection: Vec2 = new Vec2();
    private _changeTimer: number = 0;
    private _nextChangeTime: number = 0;

    init() {
        this._rigidbody = this.node.getComponent(RigidBody2D);
        this._originPos = this.node.getWorldPosition().clone();
        this.randomizeDirection();
        this.resetChangeTimer();
    }

    update(deltaTime: number) {
        if (!this._isRunning || !this._rigidbody) return;

        // 更新方向改变计时器
        this._changeTimer += deltaTime;
        if (this._changeTimer >= this._nextChangeTime) {
            this.changeDirection();
            this.resetChangeTimer();
        }

        // 检查是否超出活动范围
        const currentPos = this.node.getWorldPosition();
        const distanceToOrigin = Vec3.distance(currentPos, this._originPos);

        if (distanceToOrigin > this.wanderRadius) {
            // 如果超出范围，转向原点
            const toOrigin = new Vec2(
                this._originPos.x - currentPos.x,
                this._originPos.y - currentPos.y
            ).normalize();

            // 平滑转向原点
            this._currentDirection = Vec2.lerp(
                new Vec2(),
                this._currentDirection,
                toOrigin,
                0.1 // 平滑系数
            ).normalize();
        }

        // 应用移动
        this._rigidbody.linearVelocity = this._currentDirection.multiplyScalar(this.moveSpeed);
    }

    private changeDirection() {
        // 在当前方向基础上随机偏转一个角度
        const angleChange = (Math.random() - 0.5) * 2 * this.maxTurnAngle;
        const currentAngle = Math.atan2(this._currentDirection.y, this._currentDirection.x);
        const newAngle = currentAngle + angleChange * Math.PI / 180;

        this._currentDirection = new Vec2(
            Math.cos(newAngle),
            Math.sin(newAngle)
        ).normalize();
    }

    private randomizeDirection() {
        const angle = Math.random() * Math.PI * 2;
        this._currentDirection = new Vec2(
            Math.cos(angle),
            Math.sin(angle)
        ).normalize();
    }

    private resetChangeTimer() {
        this._changeTimer = 0;
        this._nextChangeTime = Math.random() * 
            (this.maxChangeInterval - this.minChangeInterval) + 
            this.minChangeInterval;
    }

    stop(immediate?: boolean) {
        super.stop(immediate);
        if (this._rigidbody) {
            this._rigidbody.linearVelocity = Vec2.ZERO;
        }
    }
} 